package com.xiaoxiao.cateye;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar;
import com.navinfo.navigation.map.MapHandler;
import com.navinfo.navigation.map.Navigator;
import com.navinfo.navigation.model.listeners.NavigatorListener;
import com.navinfo.navigation.navigator.NaviEngine;
import com.navinfo.navigation.navigator.NaviText;
import com.navinfo.navigation.layers.MapEventsReceiver;
import com.navinfo.smap.BaseMapActivity;
import com.xiaoxiao.cateye.library.mapwidget.CatEyeMapScaleBar;
import com.xiaoxiao.cateye.library.util.MapFileFilter;
import com.xiaoxiao.cateye.library.util.SqliteFileFilter;
import com.xiaoxiao.cateye.library.util.TabFileFilter;
import com.xiaoxiao.source.LocalRasterTileSource;
import com.xiaoxiao.source.NavinfoGeoJsonTileSource;
import com.xiaoxiao.source.NavinfoMvtTileSource;
import com.xiaoxiao.source.SMapRastorTileSource;
import com.xiaoxiao.source.SMapVectorTileSource;
import com.xiaoxiao.spatialite.SpatialiteTileSource;

import org.gdal.gdal.gdal;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Feature;
import org.gdal.ogr.Geometry;
import org.gdal.ogr.ogr;
import org.oscim.android.canvas.AndroidBitmap;
import org.oscim.backend.CanvasAdapter;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Color;
import org.oscim.backend.canvas.Paint;
import org.oscim.core.GeoPoint;
import org.oscim.core.MapPosition;
import org.oscim.core.Tile;
import org.oscim.event.Event;
import org.oscim.layers.Layer;
import org.oscim.layers.MapEventLayer;
import org.oscim.layers.TileGridLayer;
import org.oscim.layers.marker.ItemizedLayer;
import org.oscim.layers.marker.MarkerItem;
import org.oscim.layers.marker.MarkerSymbol;
import org.oscim.layers.tile.bitmap.BitmapTileLayer;
import org.oscim.layers.tile.buildings.BuildingLayer;
import org.oscim.layers.tile.vector.OsmTileLayer;
import org.oscim.layers.tile.vector.VectorTileLayer;
import org.oscim.layers.tile.vector.labeling.LabelLayer;
import org.oscim.layers.vector.PathLayer;
import org.oscim.layers.vector.VectorLayer;
import org.oscim.layers.vector.geometries.LineDrawable;
import org.oscim.layers.vector.geometries.PolygonDrawable;
import org.oscim.layers.vector.geometries.Style;
import org.oscim.map.Map;
import org.oscim.renderer.BitmapRenderer;
import org.oscim.renderer.GLViewport;
import org.oscim.renderer.bucket.TextureItem;
import org.oscim.scalebar.DefaultMapScaleBar;
import org.oscim.scalebar.ImperialUnitAdapter;
import org.oscim.scalebar.MapScaleBar;
import org.oscim.scalebar.MapScaleBarLayer;
import org.oscim.scalebar.MetricUnitAdapter;
import org.oscim.theme.ThemeLoader;
import org.oscim.theme.VtmThemes;
import org.oscim.tiling.source.OkHttpEngine;
import org.oscim.tiling.source.UrlTileSource;
import org.oscim.tiling.source.mapfile.MapFileTileSource;
import org.oscim.tiling.source.mapfile.MultiMapFileTileSource;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import me.rosuh.filepicker.config.FilePickerConfig;
import me.rosuh.filepicker.config.FilePickerManager;
import okhttp3.Cache;
import okhttp3.OkHttpClient;

public class MainActivity extends BaseMapActivity implements View.OnClickListener {
    private View rootView,layer_top_nav;
    private Button btn_load_local_map, btn_load_local_sqlite, btn_start_nav, btn_load_raster_data, btn_read_tab;
    private VectorTileLayer mapFileTileLayer;
    private CheckBox chk_layer_smap_raster,chk_layer_smap_vertor,chk_line_add_point, chk_road_arrow;
    private Layer mBitmapLayer,mVectorTileLayer, mapScaleBarLayer, gridLayer, pathLayer/*绘制线的测试图层*/, roadArrowLayer/*道路方向图层*/;
    private VectorLayer tabVectorLayer; // 用来显示tab数据的图层
    private Style vectorLayerStyle;
    private ItemizedLayer markerLayer; // 显示marker的图层

    private GeoPoint naviStartPoint, naviEndPoint;
    private OkHttpClient okHttpClient;
    private static Location mCurrentLocation;
    private Location mLastLocation;
    // 申请动态权限
    private int PERMISSION_REQUEST = 1;
    private static String customRootPath = Environment.getExternalStorageDirectory().getAbsolutePath();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = LayoutInflater.from(this).inflate(R.layout.activity_main,null);
        setContentView(rootView);
        initView();
        NaviText.initTextList(this);
        okHttpClient = new OkHttpClient();

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST);
        }
        boolean state = Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED );
        if (state) {
            if (Build.VERSION.SDK_INT >= 29) {
                //Android10之后
                customRootPath = getExternalFilesDir( null ).getAbsolutePath();
            } else {
                customRootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            }
        } else {
            customRootPath = Environment.getRootDirectory().getAbsolutePath();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, Do the you need to do.
                    Toast.makeText(getApplicationContext(), "permission was granted", Toast.LENGTH_SHORT).show();

                } else {

                    // permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MainApplication.lockOrientation(this);
    }

//    private final String[] dataSourceArray = {"Waterface", "Road", "Greenface", "Railway", "Ptline", "Villtown", "Adminflag", "Annotation"};
    private final String[] dataSourceArray = {"Waterface", "Road", "Greenface", "Railway"};
    private void initView(){
        mMapView = findViewById(R.id.mainMapView);
        MainApplication.cateyeMapView = this.mMapView;
        mMap = mMapView.map();
        mMap.layers().addGroup(0);
        mMap.layers().addGroup(1);
        mMap.layers().addGroup(2);
        mMap.layers().addGroup(3);
        mMap.layers().addGroup(4);
        mMap.layers().addGroup(5);
        if (mapScaleBarLayer == null) {
            CatEyeMapScaleBar mMapScaleBar = new CatEyeMapScaleBar(mMap);
            mMapScaleBar.setScaleBarMode(DefaultMapScaleBar.ScaleBarMode.BOTH);
            mMapScaleBar.setDistanceUnitAdapter(MetricUnitAdapter.INSTANCE);
            mMapScaleBar.setSecondaryDistanceUnitAdapter(ImperialUnitAdapter.INSTANCE);
            mMapScaleBar.setScaleBarPosition(MapScaleBar.ScaleBarPosition.BOTTOM_LEFT);
            MapScaleBarLayer mapScaleBarLayer = new MapScaleBarLayer(mMap, mMapScaleBar);
            BitmapRenderer renderer = mapScaleBarLayer.getRenderer();
            renderer.setPosition(GLViewport.Position.BOTTOM_LEFT);
            renderer.setOffset(5 * CanvasAdapter.getScale(), 0);
            mMap.layers().add(mapScaleBarLayer, 5);
        }
        MainApplication.cateyeMap = this.mMap;

        // 自动加载china.map文件
        btn_load_local_map = findViewById(R.id.btn_load_local_map);
        btn_load_local_map.setOnClickListener(this);
        btn_load_local_sqlite = findViewById(R.id.btn_load_local_sqlite);
        btn_load_local_sqlite.setOnClickListener(this);
        btn_start_nav = findViewById(R.id.btn_start_nav);
        btn_start_nav.setOnClickListener(this);
        btn_load_raster_data = findViewById(R.id.btn_load_raster_data);
        btn_load_raster_data.setOnClickListener(this);
        btn_read_tab = findViewById(R.id.btn_read_tab);
        btn_read_tab.setOnClickListener(this);
        layer_top_nav = findViewById(R.id.map_nav_top);

        chk_layer_smap_raster = findViewById(R.id.chk_layer_smap_raster);
        chk_layer_smap_raster.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    SMapRastorTileSource sMapRasterTileSource=SMapRastorTileSource.builder().httpFactory(new OkHttpEngine.OkHttpFactory()).build();
                    mBitmapLayer = new BitmapTileLayer(mMap, sMapRasterTileSource);
                    mMap.layers().add(mBitmapLayer, 3);
                    mMap.updateMap();
                } else {
                    mMap.layers().remove(mMap.layers().size()-1);
                }
            }
        });
        chk_layer_smap_vertor = findViewById(R.id.chk_layer_smap_vector);
        chk_layer_smap_vertor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    for (String dataSource: dataSourceArray) {
                        SMapVectorTileSource sMapVectorTileSource=SMapVectorTileSource.builder().locale("zh").zoomMin(12).dataSource(dataSource).httpFactory(new OkHttpEngine.OkHttpFactory()).build();
                        mVectorTileLayer = new OsmTileLayer(mMap);
                        ((OsmTileLayer)mVectorTileLayer).setRenderTheme(ThemeLoader.load(VtmThemes.MAPZEN));
                        ((OsmTileLayer)mVectorTileLayer).setTileSource(sMapVectorTileSource);
                        mMap.layers().add(mVectorTileLayer, 4);
                        mMap.layers().add(new LabelLayer(mMap, (VectorTileLayer) mVectorTileLayer), 5);
                        mMap.layers().add(new BuildingLayer(mMap, (VectorTileLayer) mVectorTileLayer), 5);
                    }
                    loadTheme(VtmThemes.SMAPRENDER.name());
                    mMap.updateMap();
                } else {
                    mMap.layers().remove(mMap.layers().size()-1);
                }
            }
        });

        chk_road_arrow = findViewById(R.id.chk_road_arrow);
        chk_road_arrow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mMap.clearMap();
                mMap.updateMap(true);
            }
        });

        // 增加绘制图层
        mMap.layers().add(new MapEventLayer(mMap), 5);
        chk_line_add_point = findViewById(R.id.chk_line_add_point);
        chk_line_add_point.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (pathLayer == null) {
                        pathLayer = new PathLayer(mMap, Color.rainbow(0.3f));
                    }
                    mMap.layers().add(pathLayer, 5);
                } else {
                    if (pathLayer!=null) {
                        mMap.layers().remove(pathLayer);
                    }
                }
            }
        });
//        initSMapLayers();
        initOnlineBgMap();
        initCustomPathLayer();
        mMap.events.bind(new Map.UpdateListener() {
            @Override
            public void onMapEvent(Event e, MapPosition mapPosition) {
                if (tabVectorLayer!=null) {
                    if (mapPosition.getZoomLevel()<12) {
                        tabVectorLayer.setEnabled(false);
                    } else {
                        tabVectorLayer.setEnabled(true);
                    }
                }
                if (markerLayer!=null) {
                    if (mapPosition.getZoomLevel()<12) {
                        markerLayer.setEnabled(false);
                    } else {
                        markerLayer.setEnabled(true);
                    }
                }
            }
        });
    }

    // 初始化请求在线底图数据
    private void initOnlineBgMap() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (true) {
            // Cache the tiles into file system
            File cacheDirectory = new File(getExternalCacheDir(), "tiles");
            int cacheSize = 200 * 1024 * 1024; // 10 MB
            Cache cache = new Cache(cacheDirectory, cacheSize);
            builder.cache(cache);
        }

        UrlTileSource tileSource = NavinfoGeoJsonTileSource.builder()
                .apiKey("4wTLZyXcQym31pxC_HGy7Q") // Put a proper API key
                .httpFactory(new OkHttpEngine.OkHttpFactory(builder))
                //.locale("en")
                .build();
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("token", "eyJhbGciOiJIUzI1NiJ9.eyJjbGllbnRJZCI6MTAzLCJ1c2VyTmFtZSI6ImFkbWluIiwidXNlcklkIjoxLCJ1c2VyR3JvdXAiOiLnoJTlj5Hpg6giLCJvcmdJZCI6MSwiaWF0IjoxNjMwOTk4MzI5LCJleHAiOjE2MzEwODQ3Mjl9.0wFm8mAA9dCC2FmZj-u1dhxTFDRYx8AqVnh2C88hitk");
        tileSource.setHttpRequestHeaders(headerMap);
//        TileCache mCache = new TileCache(MainActivity.this, getExternalCacheDir().getAbsolutePath(), "NMPGeoJsonTileSource");
//        mCache.setCacheSize(512 * (1 << 20));
//        tileSource.setCache(mCache);
        VectorTileLayer l = new VectorTileLayer(mMap, tileSource);
        mMap.layers().add(l, 5);
        mMap.layers().add(new LabelLayer(mMap, l), 5);
        mMap.layers().add(new BuildingLayer(mMap, l), 5);

        if (gridLayer == null) {
            mMap.layers().add(new TileGridLayer(mMap), 5);
        }

//        l.setTheme(ThemeLoader.load(VtmThemes.DEFAULT));
        loadTheme(null);
        mMap.updateMap(true);
    }

    private void initCustomPathLayer() {
//        String polygonStr1 = "POLYGON((115.7741591 39.6108459,115.7741591 39.6082299,115.7740201 39.6082009,115.7737901 39.6082209,115.7735701 39.6083509,115.7729101 39.6088709,115.7726901 39.6089409,115.7725501 39.6090009,115.7724801 39.6090909,115.7724701 39.6093009,115.7726001 39.6095409,115.7727201 39.6096209,115.7728401 39.6097209,115.7728901 39.6098209,115.7728901 39.6100609,115.7729301 39.6103709,115.7730401 39.6106209,115.7731701 39.6107209,115.7733901 39.6107809,115.7734301 39.6108609,115.7733701 39.6111909,115.7733801 39.6112109,115.7734001 39.6112209,115.7737901 39.6113109,115.7738101 39.6113109,115.7738301 39.6113009,115.7741001 39.6109409,115.7741591 39.6108459))";
        String polygonStr1 = "POLYGON((115.7736928 39.6082779,115.7736928 39.6112879,115.7737908 39.6113109,115.7738108 39.6113109,115.7738308 39.6113009,115.7741008 39.6109409,115.7745808 39.6101709,115.7750508 39.6098009,115.7756108 39.6094609,115.7760508 39.6090309,115.7761708 39.6088709,115.7762208 39.6087409,115.7761908 39.6086809,115.7755908 39.6085409,115.7755708 39.6085409,115.7755508 39.6085509,115.7755408 39.6085709,115.7754008 39.6090809,115.7753308 39.6095809,115.7753108 39.6096009,115.7752808 39.6096109,115.7752508 39.6096009,115.7752208 39.6095709,115.7753008 39.6089909,115.7754308 39.6085309,115.7754308 39.6085109,115.7754108 39.6085009,115.7747308 39.6083509,115.7740208 39.6082009,115.7737908 39.6082209,115.7736928 39.6082779))";
        if (pathLayer == null) {
            pathLayer = new PathLayer(mMap, Color.BLUE);
        }
        mMap.layers().add(pathLayer, 5);
        List<GeoPoint> geoPoints = GeometryTools.getGeoPoints(polygonStr1);
        ((PathLayer)pathLayer).addPoints(geoPoints);
        mMap.updateMap();

        mMap.animator().animateTo(geoPoints.get(0));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_load_local_map: // 点击加载本地地图文件
                FilePickerManager.INSTANCE
                        .from(MainActivity.this)
                        .storageType("", FilePickerConfig.STORAGE_CUSTOM_ROOT_PATH)
                        .filter(new MapFileFilter())
                        .forResult(MapFileFilter.REQUEST_CODE);
                break;
            case R.id.btn_load_raster_data: // 点击加载本地栅格数据
                FilePickerManager.INSTANCE
                        .from(MainActivity.this)
                        .storageType("", FilePickerConfig.STORAGE_CUSTOM_ROOT_PATH+"/FastMapParking/data/rsimage/PCMap/0001")
                        .skipDirWhenSelect(false)
                        .forResult(0x103);
                break;
            case R.id.btn_load_local_sqlite: // 点击加载本地sqlite文件
                FilePickerManager.INSTANCE
                        .from(MainActivity.this)
                        .storageType("", FilePickerConfig.STORAGE_CUSTOM_ROOT_PATH)
                        .filter(new SqliteFileFilter())
                        .forResult(SqliteFileFilter.REQUEST_CODE);
                break;
            case R.id.btn_start_nav: // 开始导航
                if (!Navigator.getNavigator().isOn()) {
                    Navigator.getNavigator().setNaviStart(MainActivity.this, true);
                    Navigator.getNavigator().setOn(true);
//                    layer_top_nav.setVisibility(View.VISIBLE);
                } else {
                    Navigator.getNavigator().setNaviStart(MainActivity.this, false);
                    Navigator.getNavigator().setOn(false);
//                    layer_top_nav.setVisibility(View.GONE);
                }
                break;
            case R.id.btn_read_tab: // 读取tab数据
                FilePickerManager.INSTANCE
                        .from(MainActivity.this)
                        .storageType("", FilePickerConfig.STORAGE_CUSTOM_ROOT_PATH)
                        .filter(new TabFileFilter())
                        .forResult(0x104);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case MapFileFilter.REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK){
                    List<String> mapFileList=FilePickerManager.INSTANCE.obtainData();
                    if (mapFileList!=null&&!mapFileList.isEmpty()){

                        for (String mapFilePath:mapFileList){
                            MultiMapFileTileSource multiMapFileTileSource = new MultiMapFileTileSource();
                            MapFileTileSource mTileSource = new MapFileTileSource();
                            mTileSource.setPreferredLanguage("zh");
                            if (mTileSource.setMapFile(mapFilePath)) {
                                multiMapFileTileSource.add(mTileSource);
                            }

//                            mTileLayer = mMap.setBaseMap(multiMapFileTileSource);
                            mapFileTileLayer = new OsmTileLayer(mMap);
                            mapFileTileLayer.setTileSource(multiMapFileTileSource);
                            mMap.layers().add(mapFileTileLayer, 1);
                            mMap.layers().add(new BuildingLayer(mMap, mapFileTileLayer), 2);
                            mMap.layers().add(new LabelLayer(mMap, mapFileTileLayer), 2);
//                            mapFileTileLayer.addHook(new VectorTileLayer.TileLoaderProcessHook() {
//                                @Override
//                                public boolean process(MapTile tile, RenderBuckets layers, MapElement element) {
//
//                                    if (element.tags.containsKey("oneway")) {
//                                        if (!chk_road_arrow.isChecked()) {
//                                            TagSet tagSet = element.tags;
//                                            Tag[] tags = tagSet.asArray();
//                                            for (int i = 0; i < tags.length; i++) {
//                                                if (tags[i].key.equals("oneway")) {
//                                                    tags[i] = new Tag("oneway", "no");
//                                                }
//                                            }
//                                            element.tags.set(tags);
//                                        } else {
//                                            TagSet tagSet = element.tags;
//                                            Tag[] tags = tagSet.asArray();
//                                            for (int i = 0; i < tags.length; i++) {
//                                                if (tags[i].key.equals("oneway")) {
//                                                    tags[i] = new Tag("oneway", "yes");
//                                                }
//                                            }
//                                            element.tags.set(tags);
//                                        }
//                                    }
//                                    return false;
//                                }
//
//                                @Override
//                                public void complete(MapTile tile, boolean success) {
//                                }
//                            });

                            if (!multiMapFileTileSource.getBoundingBox().contains(mMap.getMapPosition().getGeoPoint())) {
                                MapPosition pos = new MapPosition();
                                pos.setByBoundingBox(multiMapFileTileSource.getBoundingBox(), Tile.SIZE * 4, Tile.SIZE * 4);
                                mMap.setMapPosition(pos);
                                mPrefs.clear();
                            }
                        }
                    }

                    if (mapScaleBarLayer == null) {
                        CatEyeMapScaleBar mMapScaleBar = new CatEyeMapScaleBar(mMap);
                        mMapScaleBar.setScaleBarMode(DefaultMapScaleBar.ScaleBarMode.BOTH);
                        mMapScaleBar.setDistanceUnitAdapter(MetricUnitAdapter.INSTANCE);
                        mMapScaleBar.setSecondaryDistanceUnitAdapter(ImperialUnitAdapter.INSTANCE);
                        mMapScaleBar.setScaleBarPosition(MapScaleBar.ScaleBarPosition.BOTTOM_LEFT);
                        MapScaleBarLayer mapScaleBarLayer = new MapScaleBarLayer(mMap, mMapScaleBar);
                        BitmapRenderer renderer = mapScaleBarLayer.getRenderer();
                        renderer.setPosition(GLViewport.Position.BOTTOM_LEFT);
                        renderer.setOffset(5 * CanvasAdapter.getScale(), 0);
                        mMap.layers().add(mapScaleBarLayer, 5);
                    }

                    if (gridLayer == null) {
                        gridLayer = new TileGridLayer(mMap);
                        mMap.layers().add(gridLayer, 5);
                    }

                    // 加载比例尺
                    loadTheme(null);
                    mMap.updateMap(true);
                } else {
                    Snackbar.make(rootView,R.string.load_local_map_failed, 3000).setAction(R.string.confirm, null).show();
                }
                break;
            case SqliteFileFilter.REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK){
                    List<String> mapFileList=FilePickerManager.INSTANCE.obtainData();
                    if (mapFileList!=null&&!mapFileList.isEmpty()){
                        for (String mapFilePath:mapFileList){
                            // 加载成功后尝试加载本地coremap数据
                            SpatialiteTileSource spatialiteTileSource=new SpatialiteTileSource(getApplicationContext(), 16, 20);
                            File sqliteFile = new File(mapFilePath);
                            if (sqliteFile.exists()&&sqliteFile.isFile()) {
                                if (spatialiteTileSource.setMapFile(mapFilePath)){
                                    VectorTileLayer spatialiteLayer=new VectorTileLayer(mMap,spatialiteTileSource);
                                    //VectorTileLayer spatialiteLayer = mMap.setBaseMap(spatialiteTileSource);
                                    mMap.layers().add(new BuildingLayer(mMap, spatialiteLayer));
                                    mMap.layers().add(new LabelLayer(mMap, spatialiteLayer));
                                    mMap.layers().add(spatialiteLayer, 4);
                                }
                            }
                        }
                    }

                    // 加载比例尺
                    loadTheme(null);
                    mMap.updateMap(true);
                } else {
                    Snackbar.make(rootView,R.string.load_local_map_failed, 3000).setAction(R.string.confirm, null).show();
                }
                break;
            case 0x103: // 用户选中文件夹，加载栅格数据
                List<String> rasterFileList=FilePickerManager.INSTANCE.obtainData();
                if (rasterFileList == null) {
                    Snackbar.make(rootView,"没有选中任何文件夹", 3000).setAction(R.string.confirm, null).show();
                }
                if (rasterFileList.size()>1) {
                    Snackbar.make(rootView,"最多选中一个文件夹", 3000).setAction(R.string.confirm, null).show();
                }
                LocalRasterTileSource mTileSource = LocalRasterTileSource.builder().url("http://"+rasterFileList.get(0)).tilePath("/{Z}/{X}/{Y}.jpg").zoomMin(2).zoomMax(20).build();
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
//                // Cache the tiles into file system
//                File cacheDirectory = new File(getExternalCacheDir(), "tiles");
//                int cacheSize = 300 * 1024 * 1024; // 300 MB
//                Cache cache = new Cache(cacheDirectory, cacheSize);
//                builder.cache(cache);

                mTileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory(builder));
                mTileSource.setHttpRequestHeaders(Collections.singletonMap("User-Agent", "vtm-android-example"));

                BitmapTileLayer rasterLayer = new BitmapTileLayer(mMap, mTileSource);
                mMap.layers().add(rasterLayer);
                break;
            case 0x104:
                List<String> tabFileList=FilePickerManager.INSTANCE.obtainData();
                if (tabFileList!=null&&!tabFileList.isEmpty()){
                    String tabFilePath = tabFileList.get(0);

                    String encoding = gdal.GetConfigOption("TAB_ENCODING", null);
                    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
                    gdal.SetConfigOption("TAB_ENCODING", "UTF-8");
                    DataSource ds = ogr.Open(tabFilePath,0);
                    if (ds == null) {
                        System.out.println("打开文件失败");
                        return;
                    }
                    System.out.println("打开文件成功");
                    org.gdal.ogr.Layer layer = ds.GetLayerByIndex(0);
                    if (layer==null){
                        System.out.println("获取第0个图层失败");
                        return;
                    }

                    layer.ResetReading();

                    if (layer.GetFeatureCount()>0) {
                        if (markerLayer == null) {
                            Bitmap bitmapPoi = new AndroidBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.apptheme_btn_check_on_holo_light));
                            MarkerSymbol symbol = new MarkerSymbol(bitmapPoi, MarkerSymbol.HotspotPlace.BOTTOM_CENTER);
                            markerLayer = new ItemizedLayer(mMap, symbol);
                            mMap.layers().add(markerLayer, 5);
                        }
                        if (vectorLayerStyle == null) {
                            try {
                                vectorLayerStyle = Style.builder()
                                        .buffer(2)
                                        .fillAlpha(1f)
                                        .fillColor(Color.RED)
                                        .scaleZoomLevel(20)
//                                        .stippleWidth(2f)
//                                        .stipple(1)
                                        .strokeWidth(4f)
                                        .strokeColor(Color.BLUE)
                                        .strokeWidth(4f)
                                        .cap(Paint.Cap.ROUND)
//                                        .texture(new TextureItem(CanvasAdapter.getBitmapAsset("", "symbols/education/school.svg")))
                                        .build();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        if (tabVectorLayer == null) {
                            tabVectorLayer = new VectorLayer(mMap);
                        }
                        if (!mMap.layers().contains(tabVectorLayer)) {
                            mMap.layers().add(tabVectorLayer, 5);
                        }
                        Feature feature;
                        int count = 0;
                        Style pointStyle = null;
                        try {
                            pointStyle = Style.builder()
                                    .texture(new TextureItem(CanvasAdapter.getBitmapAsset("", "symbols/education/school.svg")))
                                    .build();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        while ((feature = layer.GetNextFeature())!=null) {
//                            long fid = feature.GetFID();
                            Geometry geometry = feature.GetGeometryRef();
//                            int iFieldCount = feature.GetFieldCount();
//                            FeatureDefn oDefn = feature.GetDefnRef();
//                            // 获取要素中的属性表内容
//                            for (int iField = 0; iField< iFieldCount; iField++)
//                            {
//                                FieldDefn oFieldDefn= oDefn.GetFieldDefn(iField);
//                                int type =oFieldDefn.GetFieldType();
//
//                                switch (type)
//                                {
//                                    case ogr.OFTString:
//                                        System.out.println(oFieldDefn.GetName()+":"+feature.GetFieldAsString(iField)+ "\t");
//                                        break;
//                                    case ogr.OFTReal:
//                                        System.out.println(oFieldDefn.GetName()+":"+feature.GetFieldAsDouble(iField)+ "\t");
//                                        break;
//                                    case ogr.OFTInteger:
//                                        System.out.println(oFieldDefn.GetName()+":"+feature.GetFieldAsInteger(iField)+ "\t");
//                                        break;
//                                    default:
//                                        System.out.println(oFieldDefn.GetName()+":"+feature.GetFieldAsString(iField)+ "\t");
//                                        break;
//                                }
//                            }

                            System.out.println("geometryName:"+geometry.GetGeometryName()+",geometryType:"+geometry.GetGeometryType());
                            // 解析Geometry的类型，根据类型绘制点、线、面
                            if ("POINT".equals(geometry.GetGeometryName().toUpperCase())) {
                                for (int i = 0; i < geometry.GetPointCount(); i++) {
                                    System.out.println(geometry.GetGeometryName()+"-"+i+":"+geometry.GetPoint(i)[0]+","+geometry.GetPoint(i)[1]);
//                                    PointDrawable pointDrawable = new PointDrawable(new GeoPoint(geometry.GetPoint(i)[1], geometry.GetPoint(i)[0]), pointStyle);
//                                    tabVectorLayer.add(pointDrawable);
                                    markerLayer.addItem(new MarkerItem("", "", new GeoPoint(geometry.GetPoint(i)[1], geometry.GetPoint(i)[0])));
                                }
                            } else if ("LINESTRING".equals(geometry.GetGeometryName().toUpperCase())) {
                                List<GeoPoint> geoPointList = new ArrayList<>();
                                for (int i = 0; i < geometry.GetPointCount(); i++) {
                                    System.out.println(geometry.GetGeometryName()+"-"+i+":"+geometry.GetPoint(i)[0]+","+geometry.GetPoint(i)[1]);
                                    geoPointList.add(new GeoPoint(geometry.GetPoint(i)[1], geometry.GetPoint(i)[0]));
                                }
                                LineDrawable lineDrawable = new LineDrawable(geoPointList, vectorLayerStyle);
                                tabVectorLayer.add(lineDrawable);
                            } else if ("POLYGON".equals(geometry.GetGeometryName().toUpperCase())) {
                                List<GeoPoint> geoPointList = new ArrayList<>();
                                for (int i = 0; i < geometry.GetPointCount(); i++) {
                                    System.out.println(geometry.GetGeometryName()+"-"+i+":"+geometry.GetPoint(i)[0]+","+geometry.GetPoint(i)[1]);
                                    geoPointList.add(new GeoPoint(geometry.GetPoint(i)[1], geometry.GetPoint(i)[0]));
                                }
                                PolygonDrawable polygonDrawable = new PolygonDrawable(geoPointList, vectorLayerStyle);
                                tabVectorLayer.add(polygonDrawable);
                            }
                            count++;
                        }
                        tabVectorLayer.update();
                        markerLayer.update();
                        mMap.updateMap(true);
                        System.out.println("一共加载了"+count+"条数据");
                    }
                }
             break;
        }
    }

    protected void loadTheme(final String styleId) {
        if (styleId==null||"".equals(styleId.trim())){
            mMap.setTheme(VtmThemes.SMAPRENDER, true);
        } else {
            mMap.setTheme(VtmThemes.valueOf(styleId), true);
        }
    }

    /**
     * Updates the users location based on the location
     *
     * @param location Location
     */
    public void updateCurrentLocation(Location location) {
        if (location != null) {
            mCurrentLocation = location;
        } else if (mLastLocation != null && mCurrentLocation == null) {
            mCurrentLocation = mLastLocation;
        }
        if (mCurrentLocation != null) {
            GeoPoint mcLatLong = new GeoPoint(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
            MapHandler.getMapHandler().addTrackPoint(this, mcLatLong);
            if (NaviEngine.getNaviEngine().isNavigating())
            {
                NaviEngine.getNaviEngine().updatePosition(this, mCurrentLocation);
            }
            MapHandler.getMapHandler().setCustomPoint(this, mcLatLong);
        } else {
        }
    }

    /**
     * 加载smap的layers
     * */
    private void initSMapLayers(){
        MapHandler.getMapHandler().init(mMapView, this);
        mMap.layers().add(new MapEventsReceiver(mMap, new MapEventsReceiver.MapGuestureListener() {

            @Override
            public void onTap(GeoPoint geoPoint) {
                // 点击绘制线
                if (chk_line_add_point!=null&&chk_line_add_point.isChecked()&&pathLayer!=null) {
                    PathLayer lineLayer = (PathLayer) pathLayer;
                    lineLayer.addPoint(geoPoint);
                    if (lineLayer.getPoints().size()>1) {
                    }
                }
            }

            @Override
            public void onLongPress(GeoPoint geoPoint) {
                // 用户长按地图
                if (geoPoint!=null) {
                    // 添加起点
                    if (!NaviEngine.getNaviEngine().isNavigating()) {
                        if (naviStartPoint == null) {
                            naviStartPoint = geoPoint;
                            Toast.makeText(MainActivity.this, "添加起点："+naviStartPoint.toString(), Toast.LENGTH_SHORT).show();
                            MapHandler.getMapHandler().setStartEndPoint(MainActivity.this, naviStartPoint, true, false);
                        } else {
                            naviEndPoint = geoPoint;
                            Toast.makeText(MainActivity.this, "添加终点："+naviEndPoint.toString(), Toast.LENGTH_SHORT).show();
                            MapHandler.getMapHandler().setStartEndPoint(MainActivity.this, naviEndPoint, false, false);
                            MapHandler.getMapHandler().calcPath(naviStartPoint.getLatitude(), naviStartPoint.getLongitude(), naviEndPoint.getLatitude(), naviEndPoint.getLongitude(), MainActivity.this);
                            // 添加导航监听
                            Navigator.getNavigator().addListener(new NavigatorListener() {
                                @Override
                                public void onStatusChanged(boolean on) {

                                }

                                @Override
                                public void onNaviStart(boolean on) {

                                }
                            });
                            // 显示导航按钮，点击按钮开始导航

                        }
                    } else {
                        Toast.makeText(MainActivity.this, "正在导航...", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onTripleTap(GeoPoint geoPoint) {
            }
        }));

    }

//    /**
//     * Updates the users location based on the location
//     *
//     * @param location Location
//     */
//    private void updateCurrentLocation(Location location) {
//        if (location != null) {
//            mCurrentLocation = location;
//        } else if (mLastLocation != null && mCurrentLocation == null) {
//            mCurrentLocation = mLastLocation;
//        }
//        if (mCurrentLocation != null) {
//            GeoPoint mcLatLong = new GeoPoint(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
//            if (Tracking.getTracking(getApplicationContext()).isTracking()) {
//                MapHandler.getMapHandler().addTrackPoint(this, mcLatLong);
//                Tracking.getTracking(getApplicationContext()).addPoint(mCurrentLocation, mapActions.getAppSettings());
//            }
//            if (NaviEngine.getNaviEngine().isNavigating())
//            {
//                NaviEngine.getNaviEngine().updatePosition(this, mCurrentLocation);
//            }
//            MapHandler.getMapHandler().setCustomPoint(this, mcLatLong);
//            mapActions.showPositionBtn.setImageResource(R.drawable.ic_my_location_white_24dp);
//        } else {
//            mapActions.showPositionBtn.setImageResource(R.drawable.ic_location_searching_white_24dp);
//        }
//    }
}
